import { useLatest, useUnmount, useCreation } from '.';
import { throttle } from 'lodash';

type noop = (...args: any[]) => any;

export interface ThrottleOptions {
  wait?: number;
  leading?: boolean;
  trailing?: boolean;
}

const useThrottleFn = <T extends noop>(fn: T, options?: ThrottleOptions) => {
  const fnRef = useLatest(fn);

  const debounced = useCreation(
    () =>
      throttle(
        (...args: Parameters<T>): ReturnType<T> => fnRef(...args),
        options?.wait ?? 1000,
        options,
      ),
    [],
  );

  useUnmount(() => {
    debounced.cancel();
  });

  return debounced;
};

export default useThrottleFn;
